package com.hck.infrastructure.persistent.repository;

import com.hck.domain.health.model.entity.HealthProfileEntity;
import com.hck.infrastructure.persistent.dao.IHealthProfileDao;
import com.hck.infrastructure.persistent.po.HealthProfile;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 健康檔案Repository實現
 */
@Repository
public class HealthProfileRepository {
    
    @Resource
    private IHealthProfileDao healthProfileDao;
    
    /**
     * 保存健康檔案
     */
    public void save(HealthProfileEntity entity) {
        HealthProfile po = new HealthProfile();
        BeanUtils.copyProperties(entity, po);
        
        if (entity.getId() == null) {
            po.setCreateTime(new Date());
            po.setUpdateTime(new Date());
            healthProfileDao.insert(po);
            entity.setId(po.getId());
        } else {
            po.setUpdateTime(new Date());
            healthProfileDao.update(po);
        }
    }
    
    /**
     * 根據用戶ID查詢健康檔案
     */
    public HealthProfileEntity findByUserId(Long userId) {
        HealthProfile po = healthProfileDao.selectByUserId(userId);
        if (po == null) {
            return null;
        }
        
        HealthProfileEntity entity = new HealthProfileEntity();
        BeanUtils.copyProperties(po, entity);
        return entity;
    }
    
    /**
     * 根據ID查詢健康檔案
     */
    public HealthProfileEntity findById(Long id) {
        HealthProfile po = healthProfileDao.selectById(id);
        if (po == null) {
            return null;
        }
        
        HealthProfileEntity entity = new HealthProfileEntity();
        BeanUtils.copyProperties(po, entity);
        return entity;
    }
    
    /**
     * 查詢所有健康檔案
     */
    public List<HealthProfileEntity> findAll() {
        List<HealthProfile> pos = healthProfileDao.selectAll();
        return pos.stream().map(po -> {
            HealthProfileEntity entity = new HealthProfileEntity();
            BeanUtils.copyProperties(po, entity);
            return entity;
        }).collect(Collectors.toList());
    }
    
    /**
     * 刪除健康檔案
     */
    public void deleteById(Long id) {
        healthProfileDao.deleteById(id);
    }
}